package com.demo.netty.tcp;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerAdapter;
import io.netty.channel.ChannelHandlerContext;
import org.apache.log4j.Logger;

import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.InetSocketAddress;

/**
 * Created by carl on 16/5/29.
 */
public class TcpHandler extends ChannelHandlerAdapter {
    private static final Logger logger = Logger.getLogger(TcpHandler.class);
    //获取收到的信息
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        InetAddress remoteAddr = ((InetSocketAddress)ctx.channel().remoteAddress()).getAddress();
        int remotePort = ((InetSocketAddress)ctx.channel().remoteAddress()).getPort();
        String remoteIp=remoteAddr.getHostAddress();
        ByteBuf buf=(ByteBuf)msg;
        ByteBuf response=null;
        byte[] req=new byte[buf.readableBytes()];
        buf.readBytes(req);
        String msgbody=new String(req,"UTF-8");
        logger.info("tcpserver recive msg = " + msgbody);

    }

    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {
        ctx.flush();
    }
    //异常处理
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // Close the connection when an exception is raised.
        ByteBuf response=null;

        ctx.write(response);
        logger.error( "Unexpected exception from tcp request"+cause.getMessage());
        ctx.close();
    }
}
